<?php

namespace app\mysql;

/**
 * 表的自动创建 应用于命令行  无法使用类的继承(原因暂时不明)
 */
class Schema
{
    //
    private $pdo;
    private $sql;

    /**
     * 生成所需的pdo对象
     */
    public function __construct()
    {
        $database = include __DIR__ . '/../../config/database.php'; // 运行在命令行下
        $dsn = $database['type'] . ":host=" . $database['hostname'] . ";dbname=" . $database['database'];
        try {
            $this->pdo = new \PDO($dsn, $database['username'], $database['password'], array(\PDO::MYSQL_ATTR_INIT_COMMAND => "SET
          NAMES'UTF8';", ));
        } catch (\Exception $e) {
            echo $e->getMessage();
            return;
        }
    }

    /**
     * 创建表
     * @param mixed $sqlFile 创建表的sql语句
     *
     * @return void
     */
    public function createTable($sqlFile)
    {
        if (is_file($sqlFile)) {
            $this->sql = file_get_contents($sqlFile);
            return $this->afterAction();
        } else {
            return false;
        }
    }

    /**
     * 检查表格是否存在
     *
     * @return void
     */
    public function tableExist($sql)
    {
        $stmt = $this->pdo->query($sql);
        return $stmt->fetchAll(\PDO::FETCH_ASSOC);
    }

    /**
     * 查询出表结构
     *
     * @return void
     */
    public function query($sql)
    {
        foreach ($this->pdo->query($sql) as $row) {
            $arr[] = $row;
        }
        return $arr;
    }

    /**
     * 后置操作
     */
    private function afterAction()
    {
        try {
            $stmt = $this->pdo->prepare($this->sql);
            $res = $stmt->execute();
        } catch (\Exception $e) {
            return false;
        }
        if ($res) {
            return true;
        } else {
            return false;
        }
    }
}
